<script setup>
import {onMounted, reactive, ref} from "vue";
import {
  addCategoryService,
  deleteCategoryBatchService,
  deleteCategoryService,
  getCategoryListService, updateCategoryService
} from "@/api/category.js";
import {ElMessage, ElMessageBox} from "element-plus";


const data = reactive({
  categoryName: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  dialogVisible: false,
  dialogTitle: '',
  categoryForm: {
    id: '',
    categoryName: '',
    publishTime: ''
  },
  rules: {
    categoryName: [
      {required: true, message: '请输入分类名称', trigger: 'blur'},
      {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
    ],
    publishTime: [
      {required: true, message: '请选择发布时间', trigger: 'blur'},
    ],
  },
  selectedRows: []
})
const formRef = ref()

// 获取分类列表
const getCategoryList = async () => {
  const res = await getCategoryListService({
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    categoryName: data.categoryName
  })
  if (res.data.code === '200') {
    data.tableData = res.data.data.list
    data.total = res.data.data.total
  } else {
    ElMessage.error(res.data.message)
  }
}

// 页面加载时加载
onMounted(() => {
  getCategoryList()
})

// 显示弹窗（新增）
const showAddDialog = () => {
  data.categoryForm = {
    id: '',
    categoryName: '',
    publishTime: ''
  }
  data.dialogTitle = '新增分类'
  data.dialogVisible = true
}

// 保存分类
const handleSaveCategory = async () => {
  try {
    await formRef.value.validate()

    if (data.categoryForm.id) {
      const res = await updateCategoryService(data.categoryForm)
      if (res.data.code === '200') {
        ElMessage.success('修改成功')
        data.dialogVisible = false
        await getCategoryList()
      }
    } else {
      const res = await addCategoryService(data.categoryForm)
      if (res.data.code === '200') {
        ElMessage.success('新增成功')
        data.dialogVisible = false
        await getCategoryList()
      }
    }
  } catch (error) {
    ElMessage.error('请填写完整信息')
  }
}


// 删除分类
const handleCategoryDelete = async (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteCategoryService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await getCategoryList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

// 重置
const refresh = async () => {
  data.categoryName = ''
  await getCategoryList()
}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  data.pageSize = newSize;
  getCategoryList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  data.pageNum = newPage;
  getCategoryList();
};

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 表格行数据
const handleSelectionChange = (val) => {
  data.selectedRows = val
}

// 文章批量删除
const handleArticleDeleteBatch = async () => {
  if (!data.selectedRows || data.selectedRows.length === 0) {
    ElMessage.warning("请先选择要删除的用户");
    return;
  }
  const ids = data.selectedRows.map(item => item.id)
  ElMessageBox.confirm(
      '当前操作将永久删除选中的用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteCategoryBatchService(ids)
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await getCategoryList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    getCategoryList()
    ElMessage.info('取消删除');
  });
}

const showUpdateDialog = (row) => {
  data.categoryForm = {
    id: row.id,
    categoryName: row.categoryName,
    publishTime: row.publishTime
  }
  data.dialogTitle = '修改分类'
  data.dialogVisible = true
}

</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="data.categoryName" clearable style="width: 240px" placeholder="请输入标题"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="getCategoryList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" icon="DocumentAdd" @click="showAddDialog">新增分类</el-button>
      <el-button type="danger" style="margin-left: 0" icon="Delete" @click="handleArticleDeleteBatch">批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="categoryName" align="center" label="文章标题"/>
        <el-table-column align="center" label="发布时间">
          <template #default="scope">
            <el-text type="info">{{ formatDate(scope.row.publishTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="showUpdateDialog(scope.row)" icon="Edit">修改</el-button>
            <el-button type="danger" icon="Delete" @click="handleCategoryDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <el-dialog v-model="data.dialogVisible" :title="data.dialogTitle" align-center width="40%" destroy-on-close>
    <el-form :model="data.categoryForm" :rules="data.rules" ref="formRef" label-width="80px"
             style="padding: 0 50px 0 0">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="data.categoryForm.categoryName" placeholder="请输入名称"/>
      </el-form-item>
      <!-- 发布时间 -->
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
            v-model="data.categoryForm.publishTime"
            type="datetime"
            placeholder="发布时间"
            format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss" style="width: 100%;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}
</style>